package com.cyf.plc.ui.fragment.set

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.EditText
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.callbacks.onPreShow
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.cyf.library.util.logi
import com.cyf.library.util.logw
import com.cyf.plc.R
import com.cyf.plc.adapter.FloorAdapter
import com.cyf.plc.adapter.RoomAdapter
import com.cyf.plc.adapter.SpaceItemDecoration
import com.cyf.plc.base.BaseFragment
import com.cyf.plc.constant.Constants
import com.cyf.plc.constant.Constants.Companion.ATTR_HUMIDITY
import com.cyf.plc.constant.Constants.Companion.ATTR_POWER
import com.cyf.plc.constant.Constants.Companion.ATTR_SET_TEMP
import com.cyf.plc.constant.Constants.Companion.ATTR_TEMP
import com.cyf.plc.databinding.FragmentSetPanelBinding
import com.cyf.plc.model.FloorWithRooms
import com.cyf.plc.model.PlcRoom
import com.cyf.plc.util.viewModelOf
import com.cyf.plc.viewmodel.PlcViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi

@ExperimentalCoroutinesApi
class SetPanelFragment : BaseFragment<PlcViewModel, FragmentSetPanelBinding>(),
    RoomAdapter.OnItemClickListener,
    FloorAdapter.OnItemClickListener {

    override fun layoutId(): Int = R.layout.fragment_set_panel

    private val mFloorAdapter: FloorAdapter by lazy { FloorAdapter(onItemClickListener = this) }

    private val mRoomAdapter: RoomAdapter by lazy { RoomAdapter(onItemClickListener = this) }

    private lateinit var mFloorList: MutableList<FloorWithRooms>

    private lateinit var mRoomList: MutableList<PlcRoom>

    @SuppressLint("UseRequireInsteadOfGet")
    override fun initView() {
        val divider = DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL)

        val drawable: Drawable = this.context?.let {
            ContextCompat.getDrawable(
                it,
                R.drawable.drawable_custom_divider
            )
        }!!
        drawable.setBounds(0, 0, 4, 0)
        divider.setDrawable(drawable)

        // Initialize RecyclerView
        mViewBinding.rvFloor.apply {
            layoutManager = LinearLayoutManager(this@SetPanelFragment.context)
            adapter = mFloorAdapter
            addItemDecoration(divider)
        }

        // Initialize RecyclerView
        mViewBinding.rvRoom.apply {
            layoutManager = GridLayoutManager(this.context, 3)
            adapter = mRoomAdapter
            addItemDecoration(SpaceItemDecoration(68))
        }
        //请求楼层列表
        mViewModel.getFloorWithRooms().observe(this, Observer {
            //获得楼层数据，加载到Recyclerview

            mFloorList = it.toMutableList()

            mFloorAdapter.submitList(mFloorList)

            //初始化第一个楼层的房间
            if (it.isNotEmpty())
                mRoomAdapter.submitList(it[0].plcRooms.toMutableList())
        })
    }

    override fun createViewModel(): PlcViewModel = viewModelOf(mViewModelProvider)

    override fun onItemClicked(plcFloor: FloorWithRooms) {
        //点击了楼层，加载房间
        mRoomList = plcFloor.plcRooms.toMutableList()
        mRoomAdapter.submitList(plcFloor.plcRooms)
    }

    override fun onItemLongClick(plcFloor: FloorWithRooms) {
        //长按了楼层，修改楼层，新增房间，删除楼层
        val myItems = listOf("修改楼层", "新增房间", "删除楼层")
        val floorId: Long? = plcFloor.plcFloor.floorId?.toLong()
        this.context?.let {
            MaterialDialog(it).show {
                listItemsSingleChoice(
                    items = myItems,
                    initialSelection = 0
                ) { dialog, index, text ->
                    when (index) {
                        0 -> {
                            //修改楼层
                            MaterialDialog(it).show {
                                onPreShow { dialog ->
                                    val etAttributeValue: EditText =
                                        dialog.getCustomView().findViewById(R.id.et_attribute_value)
                                    etAttributeValue.setText(plcFloor.plcFloor.floorName)
                                }

                                customView(R.layout.dialog_attribute)
                                positiveButton(R.string.attribute) { dialog ->

                                    val etAttributeValue: EditText =
                                        dialog.getCustomView().findViewById(R.id.et_attribute_value)
                                    plcFloor.plcFloor.floorName = etAttributeValue.text.toString()
                                    mViewModel.saveFloor(plcFloor.plcFloor)
                                    //更新楼层名称
                                    mFloorAdapter.notifyDataSetChanged()
                                }
                                negativeButton(android.R.string.cancel)
                                lifecycleOwner(this@SetPanelFragment)
                            }
                        }
                        1 -> {
                            //新增房间
                            MaterialDialog(it).show {
                                onPreShow { dialog ->

                                }

                                customView(R.layout.dialog_attribute)
                                positiveButton(R.string.agree) { dialog ->
                                    val etAttributeValue: EditText = dialog.getCustomView().findViewById(R.id.et_attribute_value)
                                    //新增房间
                                    val plcRoom = PlcRoom(null, etAttributeValue.text.toString(), floorId)
                                    mViewModel.saveRoom(plcRoom)
                                }
                                negativeButton(android.R.string.cancel)
                                lifecycleOwner(this@SetPanelFragment)
                            }
                        }
                        2 -> {
                            "删除楼层".logw()
                            //删除楼层下房间
                            mViewModel.deleteRooms(plcFloor.plcRooms)
                            //删除楼层
                            mViewModel.deleteFloor(plcFloor.plcFloor)
                            //刷新适配器
                            mFloorList.remove(plcFloor)
                            println("删除之后:$mFloorList")
                            mFloorAdapter.submitList(mFloorList)
                        }
                        else -> {
                        }
                    }
                }
                lifecycleOwner(this@SetPanelFragment)
            }
        }
    }

    override fun onItemClicked(plcRoom: PlcRoom, view: View) {
        //点击了房间
        val plcAttributeNewIds = ArrayList<String>()
        for (plcAttributeId in Constants.PANEL_ATTR_IDS) {
            plcAttributeNewIds.add(plcRoom.roomId.toString() + Constants.UNDERLINE + plcAttributeId)
        }
        mViewModel.getPlcAttributes(plcAttributeNewIds.toTypedArray()).observe(viewLifecycleOwner,
            Observer { it ->
                "List:$it".logi()
                context?.let { it1 ->
                    MaterialDialog(it1).show {
                        onPreShow { dialog ->
                            //初始化属性
                            val etAttributeValue1: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_1)
                            val etAttributeValue2: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_2)
                            val etAttributeValue3: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_3)
                            val etAttributeValue4: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_4)
                            it.forEach {
                                when (it.attributeName) {
                                    ATTR_SET_TEMP -> {
                                        etAttributeValue1.setText(it.offSet.toString())
                                    }
                                    ATTR_TEMP -> {
                                        etAttributeValue2.setText(it.offSet.toString())
                                    }
                                    ATTR_POWER -> {
                                        etAttributeValue3.setText(it.offSet.toString())
                                    }
                                    ATTR_HUMIDITY -> {
                                        etAttributeValue4.setText(it.offSet.toString())
                                    }
                                }
                            }
                        }
                        customView(R.layout.dialog_panel_attribute)
                        positiveButton(R.string.sure) { dialog ->
                            //修改属性列表

                            val etAttributeValue1: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_1)
                            val etAttributeValue2: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_2)
                            val etAttributeValue3: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_3)
                            val etAttributeValue4: EditText =
                                dialog.getCustomView().findViewById(R.id.et_attribute_value_4)

                            it.forEach {
                                when (it.attributeName) {
                                    ATTR_SET_TEMP -> {
                                        it.offSet = etAttributeValue1.text.toString().toInt()
                                    }
                                    ATTR_TEMP -> {
                                        it.offSet = etAttributeValue2.text.toString().toInt()
                                    }
                                    ATTR_POWER -> {
                                        it.offSet = etAttributeValue3.text.toString().toInt()
                                    }
                                    ATTR_HUMIDITY -> {
                                        it.offSet = etAttributeValue4.text.toString().toInt()
                                    }
                                }
                            }
                        }
                        negativeButton(android.R.string.cancel)
                        lifecycleOwner(this@SetPanelFragment)
                    }
                }

            })
    }

    override fun onItemLongClick(plcRoom: PlcRoom, view: View) {
        //长按了房间
        this.context?.let {
            MaterialDialog(it).show {
                title(R.string.delete)
                positiveButton(R.string.agree) { dialog ->
                    // Do something
                    mViewModel.deleteRoom(plcRoom)
                }
                negativeButton(R.string.disagree) { dialog ->
                    // Do something
                }
                lifecycleOwner(this@SetPanelFragment)
            }
        }
    }

}